package view;


import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

import controller.command.Command;
import controller.Control;
import controller.command.Save;

import model.spring.AbstractAddress;
import model.spring.AddressList;

public abstract class AbstractAddressView extends JFrame {

	private static final long serialVersionUID = -4716878239216423992L;
	
	protected AbstractAddress address;
	protected AbstractAddress bkp;
	protected AddressListView alv;
	protected Control ctrl = Control.getInstance();
	protected Command add;
	
	public AbstractAddressView(AddressListView alv) {
		this.alv = alv;
		initabstract();
		populateFields();
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.setVisible(true);
	}
	
	public void initabstract() {
		address = init();
		JButton saveButton = new JButton("Save");
		if (alv.getSelectedIndex() != -1)
			bkp = AddressList.getInstance().get(alv.getSelectedIndex()).clone();
		add = new Save(address,bkp,alv.getSelectedIndex());
		
		saveButton.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				retrieveFields();
				
				Control.getInstance().storeAndExecute(add);
				alv.clearListSelection();
				Container container = (Container) e.getSource();
				while (!(container instanceof JFrame)) {
					container = container.getParent();
				}
				((JFrame) container).setVisible(false);
				((JFrame) container).dispose();
			}
		});
		this.add(saveButton, BorderLayout.SOUTH);
		this.pack();
	}

	protected abstract AbstractAddress init();
	protected abstract void populateFields();
	protected abstract void retrieveFields();
}
